import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import QtGraphicalEffects 1.15
import QtQuick.Dialogs 1.3

/**
 * 历史查询页
 * 支持时间范围选择和数据导出
 * 
 * 布局优化：最大化表格数据显示区域
 * - 可用区域：约794px宽 × 738px高（1024-200-30 × 768-30）
 * - 标题栏：40px（压缩）
 * - 查询面板：140px（压缩，紧凑布局）
 * - 数据列表：剩余空间（约558px）- 最大化显示
 */
Item {
    id: root

    // 查询参数
    property int selectedMeterId: -1  // -1表示所有电表
    property var startDate: new Date()
    property var endDate: new Date()
    property bool isQuerying: false

    // 查询结果
    property var historyData: []  // 全部数据
    property var displayData: []  // 当前页显示的数据
    property int totalCount: 0
    
    // 分页参数
    property int pageSize: 50  // 每页50条
    property int currentPage: 1  // 当前页码（从1开始）
    property int totalPages: 0  // 总页数
    
    // 消息提示属性
    property string exportMessage: ""
    property bool showExportMessage: false
    
    // 消息提示定时器
    Timer {
        id: messageTimer
        interval: 4000
        running: false
        repeat: false
        onTriggered: {
            root.showExportMessage = false
        }
    }

    ColumnLayout {
        anchors.fill: parent
        spacing: 10

        // 页面标题（压缩高度）
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 40
            color: "white"
            radius: 8

            RowLayout {
                anchors.fill: parent
                anchors.margins: 10
                spacing: 10

                Text {
                    text: "📈 历史数据查询"
                    font.pixelSize: 16
                    font.bold: true
                    color: "#2c3e50"
                }

                Item {
                    Layout.fillWidth: true
                }

                Text {
                    text: "总计: " + root.totalCount + " 条记录"
                    font.pixelSize: 11
                    color: "#7f8c8d"
                }
            }
        }

        // 查询条件面板（压缩高度）
        Rectangle {
            Layout.fillWidth: true
            Layout.preferredHeight: 140
            Layout.maximumHeight: 140
            color: "white"
            radius: 8

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 8
                spacing: 5

                Text {
                    text: "🔍 查询条件"
                    font.pixelSize: 12
                    font.bold: true
                    color: "#2c3e50"
                }

                GridLayout {
                    Layout.fillWidth: true
                    columns: 2
                    rowSpacing: 5
                    columnSpacing: 10

                    // 电表选择
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 10

                        Text {
                            text: "电表选择:"
                            font.pixelSize: 10
                            color: "#2c3e50"
                            Layout.preferredWidth: 60
                        }

                        ComboBox {
                            id: meterCombo
                            Layout.fillWidth: true
                            implicitHeight: 26
                            font.pixelSize: 9
                            model: ["全部电表", "配电室A (1-40)", "配电室B (41-80)", "配电室C (81-120)", "指定电表..."]
                            
                            onCurrentIndexChanged: {
                                if (currentIndex === 4) {
                                    meterIdField.visible = true
                                } else {
                                    meterIdField.visible = false
                                    switch(currentIndex) {
                                        case 0: root.selectedMeterId = -1; break
                                        case 1: root.selectedMeterId = 1; break  // 示例：配电室A第一台
                                        case 2: root.selectedMeterId = 41; break // 示例：配电室B第一台
                                        case 3: root.selectedMeterId = 81; break // 示例：配电室C第一台
                                    }
                                }
                            }
                        }

                        TextField {
                            id: meterIdField
                            visible: false
                            Layout.preferredWidth: 70
                            implicitHeight: 26
                            placeholderText: "电表ID"
                            font.pixelSize: 9
                            validator: IntValidator { bottom: 1; top: 120 }
                            
                            onTextChanged: {
                                if (text.length > 0) {
                                    root.selectedMeterId = parseInt(text)
                                }
                            }
                        }
                    }

                    // 时间范围快捷选择
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 6

                        Text {
                            text: "快捷选择:"
                            font.pixelSize: 10
                            color: "#2c3e50"
                            Layout.preferredWidth: 60
                        }

                        Row {
                            spacing: 4

                            Button {
                                text: "1小时"
                                font.pixelSize: 9
                                implicitHeight: 26
                                padding: 3
                                onClicked: setTimeRange(1, "hour")
                            }

                            Button {
                                text: "24小时"
                                font.pixelSize: 9
                                implicitHeight: 26
                                padding: 3
                                onClicked: setTimeRange(24, "hour")
                            }

                            Button {
                                text: "7天"
                                font.pixelSize: 9
                                implicitHeight: 26
                                padding: 3
                                onClicked: setTimeRange(7, "day")
                            }

                            Button {
                                text: "30天"
                                font.pixelSize: 9
                                implicitHeight: 26
                                padding: 3
                                onClicked: setTimeRange(30, "day")
                            }
                        }
                    }

                    // 开始时间
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 4

                        Text {
                            text: "开始时间:"
                            font.pixelSize: 10
                            color: "#2c3e50"
                            Layout.preferredWidth: 60
                        }

                        TextField {
                            id: startDateField
                            Layout.preferredWidth: 90
                            implicitHeight: 26
                            text: Qt.formatDateTime(root.startDate, "yyyy-MM-dd")
                            font.pixelSize: 9
                            readOnly: true
                        }

                        Button {
                            text: "📅"
                            font.pixelSize: 10
                            implicitHeight: 26
                            implicitWidth: 28
                            padding: 3
                            onClicked: {
                                // TODO: 打开日期选择器
                                console.log("日期选择器待实现")
                            }
                        }

                        TextField {
                            id: startTimeField
                            Layout.preferredWidth: 68
                            implicitHeight: 26
                            text: Qt.formatDateTime(root.startDate, "HH:mm:ss")
                            font.pixelSize: 9
                        }
                    }

                    // 结束时间
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 4

                        Text {
                            text: "结束时间:"
                            font.pixelSize: 10
                            color: "#2c3e50"
                            Layout.preferredWidth: 60
                        }

                        TextField {
                            id: endDateField
                            Layout.preferredWidth: 90
                            implicitHeight: 26
                            text: Qt.formatDateTime(root.endDate, "yyyy-MM-dd")
                            font.pixelSize: 9
                            readOnly: true
                        }

                        Button {
                            text: "📅"
                            font.pixelSize: 10
                            implicitHeight: 26
                            implicitWidth: 28
                            padding: 3
                            onClicked: {
                                // TODO: 打开日期选择器
                                console.log("日期选择器待实现")
                            }
                        }

                        TextField {
                            id: endTimeField
                            Layout.preferredWidth: 68
                            implicitHeight: 26
                            text: Qt.formatDateTime(root.endDate, "HH:mm:ss")
                            font.pixelSize: 9
                        }
                    }
                }

                // 查询按钮行
                Row {
                    Layout.fillWidth: true
                    spacing: 6
                    Layout.topMargin: 2

                    Button {
                        text: "🔍 查询"
                        font.pixelSize: 10
                        font.bold: true
                        implicitWidth: 75
                        implicitHeight: 28
                        enabled: !root.isQuerying
                        
                        onClicked: {
                            queryHistoryData()
                        }
                    }

                    Button {
                        text: "🔄 重置"
                        font.pixelSize: 10
                        implicitWidth: 75
                        implicitHeight: 28
                        
                        onClicked: {
                            resetQuery()
                        }
                    }

                    Item {
                        width: 8
                        height: 1
                    }

                    Button {
                        text: "📥 导出CSV"
                        font.pixelSize: 10
                        implicitWidth: 80
                        implicitHeight: 28
                        enabled: root.historyData.length > 0
                        
                        onClicked: {
                            exportToCSV()
                        }
                    }
                }
            }
        }

        // 查询结果区域
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            color: "white"
            radius: 8

            ColumnLayout {
                anchors.fill: parent
                anchors.margins: 8
                spacing: 6

                // 结果标题栏（压缩）
                RowLayout {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 30

                    Text {
                        text: "📋 查询结果"
                        font.pixelSize: 12
                        font.bold: true
                        color: "#2c3e50"
                    }

                    Item {
                        Layout.fillWidth: true
                    }
                }

                // 加载指示器
                BusyIndicator {
                    Layout.alignment: Qt.AlignHCenter
                    running: root.isQuerying
                    visible: root.isQuerying
                }

                // 空数据提示
                Rectangle {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    color: "#f8f9fa"
                    radius: 4
                    visible: !root.isQuerying && root.historyData.length === 0

                    ColumnLayout {
                        anchors.centerIn: parent
                        spacing: 15

                        Text {
                            text: "📂"
                            font.pixelSize: 48
                            color: "#bdc3c7"
                            Layout.alignment: Qt.AlignHCenter
                        }

                        Text {
                            text: "暂无数据"
                            font.pixelSize: 16
                            color: "#7f8c8d"
                            Layout.alignment: Qt.AlignHCenter
                        }

                        Text {
                            text: "请设置查询条件并点击查询按钮"
                            font.pixelSize: 13
                            color: "#95a5a6"
                            Layout.alignment: Qt.AlignHCenter
                        }
                    }
                }

                // 表格视图
                ScrollView {
                    Layout.fillWidth: true
                    Layout.fillHeight: true
                    clip: true
                    visible: !root.isQuerying && root.historyData.length > 0

                    ListView {
                        id: historyTableView
                        model: root.displayData
                        spacing: 1

                        header: Rectangle {
                            width: historyTableView.width
                            height: 30
                            color: "#34495e"

                            Row {
                                anchors.fill: parent
                                anchors.margins: 6
                                spacing: 4

                                Text { width: 55; text: "电表ID"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 125; text: "时间"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: "Ua (V)"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: "Ub (V)"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: "Uc (V)"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: "Ia (A)"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: "Ib (A)"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: "Ic (A)"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 80; text: "平均电压"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 80; text: "平均电流"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 80; text: "总功率"; font.pixelSize: 10; font.bold: true; color: "white"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                            }
                        }

                        delegate: Rectangle {
                            width: historyTableView.width
                            height: 30
                            color: index % 2 === 0 ? "white" : "#f8f9fa"

                            Row {
                                anchors.fill: parent
                                anchors.margins: 6
                                spacing: 4

                                Text { width: 55; text: modelData.meterId; font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 125; text: Qt.formatDateTime(modelData.timestamp, "yyyy-MM-dd HH:mm:ss"); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: modelData.ua.toFixed(1); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: modelData.ub.toFixed(1); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: modelData.uc.toFixed(1); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: modelData.ia.toFixed(2); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: modelData.ib.toFixed(2); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 65; text: modelData.ic.toFixed(2); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 80; text: ((modelData.ua + modelData.ub + modelData.uc) / 3).toFixed(1); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 80; text: ((modelData.ia + modelData.ib + modelData.ic) / 3).toFixed(2); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                                Text { width: 80; text: (((modelData.ua * modelData.ia + modelData.ub * modelData.ib + modelData.uc * modelData.ic) / 1000)).toFixed(2); font.pixelSize: 10; color: "#2c3e50"; verticalAlignment: Text.AlignVCenter; elide: Text.ElideRight }
                            }
                        }
                    }
                }

                // 图表视图已删除

                // 分页控件（压缩）
                RowLayout {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 32
                    spacing: 6
                    visible: !root.isQuerying && root.historyData.length > 0

                    Text {
                        text: "每页 " + root.pageSize + " 条"
                        font.pixelSize: 10
                        color: "#7f8c8d"
                    }

                    Item {
                        Layout.fillWidth: true
                    }

                    Button {
                        text: "首页"
                        font.pixelSize: 10
                        padding: 4
                        implicitHeight: 26
                        enabled: root.currentPage > 1
                        onClicked: goToPage(1)
                    }

                    Button {
                        text: "上一页"
                        font.pixelSize: 10
                        padding: 4
                        implicitHeight: 26
                        enabled: root.currentPage > 1
                        onClicked: goToPage(root.currentPage - 1)
                    }

                    Text {
                        text: "第 " + root.currentPage + " / " + root.totalPages + " 页"
                        font.pixelSize: 10
                        color: "#2c3e50"
                    }

                    Button {
                        text: "下一页"
                        font.pixelSize: 10
                        padding: 4
                        implicitHeight: 26
                        enabled: root.currentPage < root.totalPages
                        onClicked: goToPage(root.currentPage + 1)
                    }

                    Button {
                        text: "末页"
                        font.pixelSize: 10
                        padding: 4
                        implicitHeight: 26
                        enabled: root.currentPage < root.totalPages
                        onClicked: goToPage(root.totalPages)
                    }
                }
            }
        }
    }
    
    // 消息提示框
    Rectangle {
        id: messageBox
        anchors.centerIn: parent
        width: 400
        height: messageText.height + 60
        radius: 8
        color: "#2c3e50"
        border.width: 2
        border.color: "#3498db"
        visible: root.showExportMessage
        z: 1000
        
        ColumnLayout {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 15
            
            Text {
                id: messageText
                Layout.fillWidth: true
                text: root.exportMessage
                font.pixelSize: 13
                color: "white"
                wrapMode: Text.WordWrap
                horizontalAlignment: Text.AlignHCenter
            }
            
            Button {
                text: "确定"
                Layout.alignment: Qt.AlignHCenter
                implicitWidth: 80
                implicitHeight: 30
                onClicked: {
                    root.showExportMessage = false
                }
            }
        }
        
        // 阴影效果
        layer.enabled: true
        layer.effect: DropShadow {
            horizontalOffset: 0
            verticalOffset: 4
            radius: 12
            samples: 16
            color: "#80000000"
        }
    }

    // TODO: 日期选择对话框需要使用自定义实现或第三方库
    // 暂时使用文本输入框代替

    // 设置时间范围
    function setTimeRange(value, unit) {
        var now = new Date()
        root.endDate = now
        
        if (unit === "hour") {
            root.startDate = new Date(now.getTime() - value * 60 * 60 * 1000)
        } else if (unit === "day") {
            root.startDate = new Date(now.getTime() - value * 24 * 60 * 60 * 1000)
        }
        
        startDateField.text = Qt.formatDateTime(root.startDate, "yyyy-MM-dd")
        startTimeField.text = Qt.formatDateTime(root.startDate, "HH:mm:ss")
        endDateField.text = Qt.formatDateTime(root.endDate, "yyyy-MM-dd")
        endTimeField.text = Qt.formatDateTime(root.endDate, "HH:mm:ss")
    }

    // 查询历史数据
    function queryHistoryData() {
        root.isQuerying = true
        
        console.log("查询历史数据:", root.selectedMeterId, root.startDate, root.endDate)
        
        // 检查historyDataBridge是否可用
        if (typeof historyDataBridge === 'undefined' || !historyDataBridge) {
            console.error("历史数据桥接不可用，无法查询数据库")
            root.isQuerying = false
            return
        }
        
        // 调用后端数据库查询
        try {
            // 格式化时间字符串
            var startTimeStr = Qt.formatDateTime(root.startDate, "yyyy-MM-dd HH:mm:ss")
            var endTimeStr = Qt.formatDateTime(root.endDate, "yyyy-MM-dd HH:mm:ss")
            
            console.log("查询参数: 电表ID=" + root.selectedMeterId + ", 开始时间=" + startTimeStr + ", 结束时间=" + endTimeStr)
            
            // 调用C++方法查询数据
            var dataList = historyDataBridge.queryHistoryData(root.selectedMeterId, startTimeStr, endTimeStr)
            
            // 更新UI
            root.historyData = dataList
            root.totalCount = dataList.length
            
            // 计算总页数
            root.totalPages = Math.ceil(root.totalCount / root.pageSize)
            if (root.totalPages === 0) root.totalPages = 1
            
            // 重置到第一页
            root.currentPage = 1
            updateDisplayData()
            
            root.isQuerying = false
            
            console.log("查询完成，共 " + root.totalCount + " 条记录，共 " + root.totalPages + " 页")
            
            // 如果图表视图已激活，则更新图表（否则等待切换到图表视图时再更新）
            if (chartViewBtn.checked) {
                updateCharts()
            }
        } catch (e) {
            console.error("查询历史数据出错:", e)
            root.isQuerying = false
        }
    }

    // 更新图表（带数据采样和延迟加载）
    function updateCharts() {
        if (!chartsLoader.active || chartsLoader.status !== Loader.Ready || !chartsLoader.item) {
            console.log("图表未就绪，跳过更新")
            return
        }
        
        // 使用定时器延迟更新，避免时序问题
        updateChartsTimer.restart()
    }
    
    // 图表逻辑已移除

    // 重置查询
    function resetQuery() {
        root.selectedMeterId = -1
        meterCombo.currentIndex = 0
        setTimeRange(24, "hour")
        root.historyData = []
        root.displayData = []
        root.totalCount = 0
        root.currentPage = 1
        root.totalPages = 0
    }

    // 更新当前页显示的数据
    function updateDisplayData() {
        if (root.historyData.length === 0) {
            root.displayData = []
            return
        }
        
        var startIndex = (root.currentPage - 1) * root.pageSize
        var endIndex = Math.min(startIndex + root.pageSize, root.historyData.length)
        
        var pageData = []
        for (var i = startIndex; i < endIndex; i++) {
            pageData.push(root.historyData[i])
        }
        
        root.displayData = pageData
        console.log("显示第 " + root.currentPage + " 页，共 " + pageData.length + " 条数据")
    }

    // 跳转到指定页
    function goToPage(page) {
        if (page < 1 || page > root.totalPages) {
            console.warn("无效的页码:", page)
            return
        }
        
        root.currentPage = page
        updateDisplayData()
    }

    // 文件保存对话框
    FileDialog {
        id: saveFileDialog
        title: "导出CSV文件"
        selectExisting: false
        selectMultiple: false
        nameFilters: ["CSV文件 (*.csv)", "所有文件 (*)"]
        folder: shortcuts.documents  // 默认到文档目录
        
        onAccepted: {
            var filePath = fileUrl.toString()
            // 移除 file:/// 前缀（Windows）
            if (filePath.startsWith("file:///")) {
                filePath = filePath.substring(8)
            } else if (filePath.startsWith("file://")) {
                filePath = filePath.substring(7)
            }
            
            // 确保文件有.csv扩展名
            if (!filePath.toLowerCase().endsWith(".csv")) {
                filePath += ".csv"
            }
            
            console.log("用户选择的导出路径:", filePath)
            performExport(filePath)
        }
        
        onRejected: {
            console.log("用户取消了导出")
        }
    }
    
    // 执行实际的导出操作
    function performExport(filePath) {
        showMessage("正在导出，请稍候...")
        
        try {
            // 格式化时间字符串
            var startTimeStr = Qt.formatDateTime(root.startDate, "yyyy-MM-dd HH:mm:ss")
            var endTimeStr = Qt.formatDateTime(root.endDate, "yyyy-MM-dd HH:mm:ss")
            
            // 调用C++方法导出
            var success = historyDataBridge.exportToCSV(root.selectedMeterId, startTimeStr, endTimeStr, filePath)
            
            if (success) {
                console.log("CSV导出成功:", filePath)
                showMessage("✅ CSV导出成功！\n文件路径: " + filePath + "\n共 " + root.totalCount + " 条记录")
            } else {
                console.error("CSV导出失败")
                showMessage("❌ CSV导出失败，请检查文件路径权限")
            }
        } catch (e) {
            console.error("导出CSV出错:", e)
            showMessage("❌ 导出出错: " + e.toString())
        }
    }
    
    // 导出CSV
    function exportToCSV() {
        console.log("导出CSV")
        
        // 检查是否有数据
        if (root.historyData.length === 0) {
            console.warn("没有数据可导出")
            showMessage("没有数据可导出，请先查询数据")
            return
        }
        
        // 检查historyDataBridge是否可用
        if (typeof historyDataBridge === 'undefined' || !historyDataBridge) {
            console.error("历史数据桥接不可用")
            showMessage("系统错误：历史数据桥接不可用")
            return
        }
        
        // 直接打开文件对话框
        // 注意：QtQuick.Dialogs 1.3 的 FileDialog 不支持预设文件名，用户需要手动输入
        saveFileDialog.open()
    }
    
    // 显示消息提示
    function showMessage(msg) {
        exportMessage = msg
        showExportMessage = true
        messageTimer.restart()
    }

    // 图表组件已移除

    Component.onCompleted: {
        console.log("HistoryPage loaded")
        setTimeRange(24, "hour")
    }
}

